#include "RF433any.h"
#include <Arduino.h>

#define PIN_RFINPUT 0 // recv pin

Track track(PIN_RFINPUT);

void output_timings(Decoder *pdec)
{
  TimingsExt tsext;
  if (!pdec)
    return;
  pdec->get_tsext(&tsext);
  Serial.printf("         I=%u, LS=%u, LL=%u, HS=%u, HL=%u, S=%u, U=%u, "
                "V=%u, Y=%u, Z=%u\n",
                tsext.initseq, tsext.low_short,
                tsext.low_long, tsext.high_short, tsext.high_long, tsext.sep,
                tsext.first_low, tsext.first_high, tsext.first_low_ignored,
                tsext.last_low);
}

void setup_recv()
{
  pinMode(PIN_RFINPUT, INPUT);
  Serial.print("Waiting for signal\n");

  track.treset();
}

void tick_recv()
{
  if (!track.do_events())
  {
    delay(1);
  }
  else
  {
    Decoder *pdec0 = track.get_data(RF433ANY_FD_ALL);

    for (Decoder *pdec = pdec0; pdec != nullptr; pdec = pdec->get_next())
    {
      Serial.print("Received ");
      Serial.print(pdec->get_nb_bits());
      Serial.print(" bits (x");
      Serial.print(pdec->get_repeats() + 1);
      Serial.print("): ");
      char *buf = pdec->get_pdata()->to_str();
      if (buf)
      {
        Serial.println(buf);
        free(buf);
      }

      output_timings(pdec);
    }
    delete pdec0;

    track.treset();
  }
}
